package controller.company;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.trek2000.android.enterprise.R;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import adapter.company.AllCompanyFeedAdapter;
import adapter.company.SelectCompanyAdapter;
import define.API;
import define.Key;
import model.company.CompanyFeedItem;
import model.company.SelectCompanyItem;
import model.company.ShotOfCompanyFeedItem;
import ui.fragment.company.AllCompanyFeedFragment;
import ui.fragment.company.SelectCompanyFragment;
import utils.Utils;

/**
 * Created by trek2000 on 19/8/2014.
 */
public class SelectCompanyAsync extends AsyncTask<String, Void, Boolean> {

    /**
     * String section
     */
    private String NAME = "";
    private String FORMAL_NAME = "";
    private long added_time = 0;
    private String LOGO_URL = "";
    private int number_of_users = 0;
    private int number_of_groups= 0;
    private long company_id = 0;
    private int company_id_group = 0;

    private String ERROR = "";
    private String STATUS = "";

    /**
     * View section
     */

    /**
     * The others section
     */
    private Context mContext;
    public static ArrayList <SelectCompanyItem> mAlSelectCompany = new ArrayList<>();
    public static ArrayList <Long> mAlCompanyId = new ArrayList<>();

    public SelectCompanyAsync(Context context) {
        this.mContext = context;
    }

    @Override
    protected Boolean doInBackground(String... params) {
        return getData(params);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //add item default all company
        long company_id_default_item = 1234567890;
        SelectCompanyItem selectCompanyAllCompanyItem = new SelectCompanyItem(
                mContext.getString(R.string.all_company), "", 0,
                "", 0, 0,
                1234567890, 0
        );
        if (!mAlCompanyId.contains(company_id_default_item)) {
            mAlSelectCompany.add(selectCompanyAllCompanyItem);
            mAlCompanyId.add(company_id_default_item);
        }

    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);

        // hide waiting dialog
        Utils.hideWaitingDialog();

        if (!result) {
            Toast.makeText(mContext, ERROR ,
                    Toast.LENGTH_SHORT).show();
        } else {
            //TODO load background select company to get data, because not yet drawer notification (drawer company just open in company feed)
            if (SelectCompanyFragment.selectCompanyAdapter != null && SelectCompanyFragment.mGvInSelectCompanyFragment != null) {
                SelectCompanyFragment.selectCompanyAdapter = new SelectCompanyAdapter(mContext, R.layout.simple_list_item_select_company, mAlSelectCompany);
                SelectCompanyFragment.mGvInSelectCompanyFragment.setAdapter(SelectCompanyFragment.selectCompanyAdapter);
            }
        }
    }

    /**
     * Basic methods
     */
    private boolean getData(String[] params) {
        HttpPost mHttpPost = new HttpPost(API.GET_ALL_COMPANY_LIST);
        List<NameValuePair> mListValues = new ArrayList<NameValuePair>();
        /**
         * user_Name
         * password
         * device_token
         * device_OS
         */
        mListValues.add(new BasicNameValuePair(Key.USER_GLOBAL_ID, params[0]));
        mListValues.add(new BasicNameValuePair(Key.ACCESS_TOKEN, params[1]));

        try {
            mHttpPost.setEntity(new UrlEncodedFormEntity(mListValues));
            HttpParams mHttpParams = new BasicHttpParams();

            int TIMEOUT_CONNECTION = 30000;
            int TIMEOUT_SOCKET = 30000;

            HttpConnectionParams.setConnectionTimeout(
                    mHttpParams, TIMEOUT_CONNECTION);
            HttpConnectionParams.setSoTimeout(mHttpParams, TIMEOUT_SOCKET);
            HttpClient mHttpclient = new DefaultHttpClient(mHttpParams);
            HttpResponse mHttpResponse;
            mHttpResponse = mHttpclient.execute(mHttpPost);
            HttpEntity mHttpEntity = mHttpResponse.getEntity();
            String XML = EntityUtils.toString(mHttpEntity);

            Log.i("", SelectCompanyAsync.class.getSimpleName() + " " + XML);

            JSONObject mJoXml = new JSONObject(XML);
            //get string in mJoXml
            STATUS = mJoXml.getString(Key.STATUS);
            if (STATUS.equals(mContext.getString(R.string.success_))) {
                //get mJaCompanies in mJoXml
                JSONArray mJaCompanies = mJoXml.getJSONArray(Key.COMPANIES);
                if (!"[]".equals(mJaCompanies.toString())) {
                    for (int i = 0; i <mJaCompanies.length(); i++) {
                        //get mJoCompanies in mJaCompanies
                        JSONObject mJoCompanies = mJaCompanies.getJSONObject(i);
                        //get string in mJoCompanies
                        NAME = mJoCompanies.getString(Key.NAME);
                        FORMAL_NAME = mJoCompanies.getString(Key.FORMALNAME);
                        added_time = mJoCompanies.getLong(Key.ADDEDTIME);
                        LOGO_URL = mJoCompanies.getString(Key.LOGO_URL);
                        number_of_users = mJoCompanies.getInt(Key.NUMBER_OF_USERS);
                        number_of_groups = mJoCompanies.getInt(Key.NUMBER_OF_GROUPS);
                        company_id = mJoCompanies.getLong(Key.COMPANY_ID);
                        company_id_group = mJoCompanies.getInt(Key.COMPANY_ID_GROUP);
                        SelectCompanyItem selectCompanyItem = new SelectCompanyItem(
                                NAME, FORMAL_NAME, added_time,
                                LOGO_URL, number_of_users, number_of_groups,
                                company_id, company_id_group
                        );
                        if (!mAlCompanyId.contains(company_id)) {
                            mAlSelectCompany.add(selectCompanyItem);
                            mAlCompanyId.add(company_id);
                        }
                    }
                }
                return  true;
            } else if (STATUS.equals(mContext.getString(R.string.error))) {
                ERROR = mJoXml.getString(Key.ERROR);
                return false;
            }
        } catch (ClassCastException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ConnectTimeoutException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}